package com.kedou.sdk.download;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class ActivitiesDownloader extends BaseDownloader{

    private static final String CACHE_DIR = "/activities/";

    private static ActivitiesDownloader instance;

    private ActivitiesDownloader() {
        super();
    }

    public static ActivitiesDownloader getImpl() {
        synchronized (ActivitiesDownloader.class) {
            if (instance == null) {
                instance = new ActivitiesDownloader();
            }
        }
        return instance;
    }

    @Override
    public File getExternalDownloadDir() {
        return new File(super.getExternalDownloadDir(), CACHE_DIR);
    }

    @Override
    public File getDownloadApkVersionFile() {
        File downloadDir = getExternalDownloadDir();

        if (downloadDir.exists()) {
            File[] childFiles = downloadDir.listFiles();
            if (childFiles != null && childFiles.length > 0) {
                for (File child : childFiles) {
                    if (child.isFile()) {
                        String filename = child.getName();
                        if (filename.endsWith(".apk") && filename.startsWith("activities_")) {
                            return child;
                        }
                    }
                }
            }
        }

        return null;
    }

    @Override
    public File randomMakeDownloadStorageFile(String extension) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA);

        StringBuilder builder = new StringBuilder("activities_");
        builder.append(extension).append("_");
        builder.append(sdf.format(new Date()));
        builder.append(".apk");
        return new File(getExternalDownloadDir(), builder.toString());
    }

}
